<?php
/**
 * @version $Id: admin.easycomments.php 283 2007-12-02 22:34:46Z elkuku $
 * @package EasyComments
 * EasyComments - A Joomla Comment Component
 * Based on akocomment
 * @license Released under the terms of the GNU General Public License (see LICENSE.php in the Joomla! root directory)
 * @Achim Raji (aka cybergurk) - David Jardin (aka SniperSister) - Cedric May - Siegmund Langsch (aka langsch2)
 **/

( defined( '_JEXEC' ) ) or ( defined( '_VALID_MOS' ) ) or die( 'Restricted access' );
echo 'not yet.... :(';
die();
#return FALSE;
require_once( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_easycomments2'.DS.'class.easycomments2.php');
require_once( $mainframe->getPath( 'admin_html' ) );

// language-files
if (file_exists($mosConfig_absolute_path.'/components/com_easycomments2/languages/'.$mosConfig_lang.'.php')) {
	include($mosConfig_absolute_path.'/components/com_easycomments2/languages/'.$mosConfig_lang.'.php');
} else {   
	include($mosConfig_absolute_path.'/components/com_easycomments2/languages/english.php');
}

$task = mosGetParam( $_REQUEST, 'task', null );
$ec_mainmode = mosGetParam( $_REQUEST, 'ec_mainmode', null );
$ec_emailcloak = intval( mosGetParam( $_REQUEST, 'emailcloak', 1) );
$ec_frontendedit = intval( mosGetParam( $_REQUEST, 'frontendedit', 1) );
#$ec_frontendedit_users = intval( mosGetParam( $_REQUEST, 'frontendedit', 1) );
$ec_notify = mosGetParam( $_REQUEST, 'ec_notify', null );
$ec_config = mosGetParam( $_REQUEST, 'ec_config', null );
$cid = mosGetParam( $_REQUEST, 'cid', array( 0 ) );
$uid = mosGetParam( $_REQUEST, 'uid', array( 0 ) );
if (!is_array( $cid )) {
	$ocid=$cid;
	$cid = array ();
	$cid[]=$ocid;
	mosArrayToInts($cid);
}

switch ($task) {
  case "new":
   editComment( $option, 0 );
   break;
  case "edit":
   editComment( $option, $cid[0] );
   break;
  case "save":
   saveComment( $option );
   break;
  case "remove":
   removeComments( $cid, $option );
   break;
  case "publish":
   publishComments( $cid, 1, $option );
   break;
  case "unpublish":
   publishComments( $cid, 0, $option );
   break;
  case "about":
   showAbout();
   break;
  case "settings":
   showConfig( $option );
   break;
  case "savesettings":
   saveConfig ($option, $ec_config, $ec_mainmode, $ec_notify, $ec_emailcloak, $ec_frontendedit );
   break;
  case "migrate":
   migratorOverview( $option );
   break;
  case "migrate_akocomment":
   migrateAkocomment( $option, $database );
   break;
  default:
   showComments( $option );
   break;
}

############################################################################

function showComments ( $option ) {
  global $database, $mainframe;
  $limit      = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
  $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
  $search     = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
  $search     = $database->getEscaped( trim( strtolower( $search ) ) );
  $where = array();
  if ($search) {
    $where[] = "LOWER(comment) LIKE '%$search%'";
  }
  $database->setQuery( "SELECT count(*) FROM #__easycomments AS a" . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "") );
  $total = $database->loadResult();
  echo $database->getErrorMsg();
  include_once( "includes/pageNavigation.php" );
  $pageNav = new mosPageNav( $total, $limitstart, $limit  );
  $database->setQuery( "SELECT * FROM #__easycomments"
    . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
    . "\nORDER BY id DESC"
    . "\nLIMIT $pageNav->limitstart,$pageNav->limit"
  );
  $rows = $database->loadObjectList();
  if ($database->getErrorNum()) {
    echo $database->stderr();
    return false;
  }
  HTML_comment::showComments( $option, $rows, $search, $pageNav );
}

############################################################################

function editComment( $option, $uid ) {
  global $database;
  $row = new moseasycomments( $database );
  $row->load( $uid );
  #Get list of Content
  $contentitem[] = mosHTML::makeOption( '0', _EASYCOMMENTS_ADMIN_SELECT_CONTENT_ITEM );
  $database->setQuery( "SELECT id AS value, title AS text FROM #__content ORDER BY title" );
  $contentitem = array_merge( $contentitem, $database->loadObjectList() );
  if (count( $contentitem ) < 1) {
    mosRedirect( "index2.php?option=com_sections&scope=content", _EASYCOMMENTS_ADMIN_ADD_CONTENT );
  }
  $clist = mosHTML::selectList( $contentitem, 'contentid', 'class="inputbox" size="1"', 'value', 'text', intval( $row->contentid ) );
  # Check if new or edit
  if ($uid) {
    $row->checkout( $my->id );
  } else {
    $row->published = 0;
  }
  # Prepare Ordering box
  $order = mosGetOrderingList( "SELECT ordering AS value, title AS text FROM #__easycomments"
    . "\nWHERE contentid='$row->contentid' ORDER BY ordering" );
  $olist = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"', 'value', 'text', intval( $row->ordering ) );
  # Build up published box
  $publist = mosHTML::yesnoRadioList( 'published', 'class="inputbox"', $row->published );
  HTML_comment::editComment( $option, $row, $clist, $olist, $publist );
}

############################################################################

function saveComment( $option ) {
  global $database;
  $row = new moseasycomments( $database );
  if (!$row->bind( $_POST )) {
    echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
    exit();
  }
  $row->date = time();
  $row->ip   = getenv('REMOTE_ADDR');
  if (!$row->store()) {
    echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
    exit();
  }
  $row->updateOrder( "contentid='$row->contentid'" );
  mosRedirect( "index2.php?option=$option" );
}

############################################################################

function publishComments( $cid=null, $publish=1,  $option ) {
  global $database;
  if (!is_array( $cid ) || count( $cid ) < 1) {
    $action = $publish ? 'publish' : 'unpublish';
    echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
    exit;
  }
  $cids = implode( ',', $cid );
  $database->setQuery( "UPDATE #__easycomments SET published='$publish' WHERE id IN ($cids)" );
  if (!$database->query()) {
    echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
    exit();
  }
  mosRedirect( "index2.php?option=$option" );
}

############################################################################

function showAbout() {
  HTML_comment::showAbout();
}

############################################################################

function migratorOverview() {
  HTML_comment::migratorOverview();
}

function cleanAkocomment ($text) {
	$text = str_replace("[B]","",$text);
	$text = str_replace("[/B]","",$text);
	$text = str_replace("[I]","",$text);
	$text = str_replace("[/I]","",$text);
	$text = str_replace("[U]","",$text);
	$text = str_replace("[/U]","",$text);
	$text = str_replace("[URL","",$text);
	$text = str_replace("[/URL]","",$text);
	$text = str_replace("[EMAIL]","",$text);
	$text = str_replace("[/EMAIL]","",$text);
	$text = str_replace("[QUOTE]","",$text);  
	$text = str_replace("[/QUOTE]","",$text);
	$text = str_replace("[CODE]","",$text);  
	$text = str_replace("[/CODE]","",$text);
	$text = str_replace("[LIST]","",$text);
	$text = str_replace("[/LIST]","",$text);
	$text = str_replace("[*]","",$text);
	$text = str_replace(":)","",$text);
	$text = str_replace(":grin","",$text);
	$text = str_replace(";)","",$text);
	$text = str_replace("8)","",$text);
	$text = str_replace(":p","",$text);
	$text = str_replace(":roll","",$text);
	$text = str_replace(":eek","",$text);
	$text = str_replace(":upset","",$text);
	$text = str_replace(":zzz","",$text);	
	$text = str_replace(":sigh","",$text);
	$text = str_replace(":?","",$text);
	$text = str_replace(":cry","",$text);
	$text = str_replace(":(","",$text);
	$text = str_replace(":x","",$text);
	return $text;
}

function migrateAkocomment($option, &$db) {
  global $mosConfig_absolute_path, $database;
  $database->setQuery( "SELECT * FROM #__akocomment");
  $oldrows = $database->loadObjectList();
  foreach( $oldrows AS $oldrow )
  {
  $row = new moseasycomments( $db );
  $row->parentid = $oldrow->parentid;
  $row->status = $oldrow->status;
  $row->contentid = $oldrow->contentid;
  $row->ip = $oldrow->ip;
  $row->name = $oldrow->name;
  $row->title = $oldrow->title;
  $row->comment = cleanAkocomment ($oldrow->comment);
  $row->date = strtotime($oldrow->date);
  $row->published = $oldrow->published;
  $row->ordering = $oldrow->ordering;
  if(!$row->store())
  {
 	echo "<font color='red'>" . _EASYCOMMENTS_ADMIN_MIGRATION_ERROR . $oldrow->id . "</font><br />";
 	break;
  }
  }
  mosRedirect( "index2.php?option=$option&task=migrate", _EASYCOMMENTS_ADMIN_MIGRATION_OK );
}

############################################################################

function showConfig( $option ) {
  global $mosConfig_absolute_path, $mosConfig_live_site, $database, $mosConfig_lang;
  
  require($mosConfig_absolute_path."/administrator/components/com_easycomments/config.easycomments.php");
  include_once( $mosConfig_absolute_path . '/administrator/components/com_easycomments/includes/snoopy.class.php' );
	if($ec_config['autoversioncheck'] == 1)
	{
		$s = new Snoopy();
		$s->read_timeout = 90;
		$s->referer = $mosConfig_live_site;		@$s->fetch('http://www.easy-joomla.org/components/com_versions/directinfo.php?catid=1');
		$version = $s->results;
		if($s->error || $s->status != 200){		
	   		$version = "<span style='border-bottom: dotted 1px #b9b9b9; padding-right: 5px; padding-left: 5px;'><b>EasyComments ".$ec_config['version']."</b></span><br /><div style='margin-top: 5px;'><a href='http://www.easy-joomla.org/index.php?option=com_versions&catid=1&myVersion=".$ec_config['version']."' target='_blank'><img src='".$mosConfig_live_site."/administrator/components/com_easycomments/images/fail.gif' border='0' style='vertical-align: middle; padding-right: 5px;'/><span style='color: #e34639;'><b>"._EASYCOMMENTS_ADMIN_CONNECTION_FAILED."</b></span></a></div>";
    	} else if($version == $ec_config['version']){
			$version = "<span style='border-bottom: dotted 1px #b9b9b9; padding-right: 5px; padding-left: 5px;'><b>EasyComments ".$ec_config['version']."</b></span><br /><div style='margin-top: 5px;'><a href='http://www.easy-joomla.org/index.php?option=com_versions&catid=1&myVersion=".$ec_config['version']."' target='_blank'><img src='".$mosConfig_live_site."/administrator/components/com_easycomments/images/shield.gif' border='0' style='vertical-align: text-bottom; padding-right: 5px;'/> <span style='color: #e2ad43;'><b>"._EASYCOMMENTS_ADMIN_NO_UPDATES."</b></span></a></div>";
    	} else {
 	  		$version = "<span style='border-bottom: dotted 1px #b9b9b9; padding-right: 5px; padding-left: 5px;'><b>EasyComments ".$ec_config['version']."</b></span><br /><div style='margin-top: 5px;'><a href='http://www.easy-joomla.org/index.php?option=com_versions&catid=1&myVersion=".$ec_config['version']."' target='_blank'><img src='".$mosConfig_live_site."/administrator/components/com_easycomments/images/box.gif' border='0' style='vertical-align: text-bottom; padding-right: 5px;'/> <span style='color: #ce763a;'><b>"._EASYCOMMENTS_ADMIN_UPDATES_AVAILABLE."</b> EasyComments " . $version . "</span></a></div>";
   		}
	} else {	
		$version = "<span style='border-bottom: dotted 1px #b9b9b9; padding-right: 5px; padding-left: 5px;'>
		<b>EasyComments ".$ec_config['version']."</b>
		</span><br /><div style='margin-top: 5px;'><a href='http://www.easy-joomla.org/index.php?option=com_versions&catid=1&myVersion=".$ec_config['version']."' target='_blank'><img src='".$mosConfig_live_site."/administrator/components/com_easycomments/images/box.gif' border='0' style='vertical-align: text-bottom; padding-right: 5px;'/><span style='color: #ce763a;'><b>"._EASYCOMMENTS_ADMIN_CHECK_FOR_NEW_UPDATES."</b></span></a></div>";
	}
$database->setQuery("UPDATE #__components SET name ='"._EASYCOMMENTS_INSTALL_MENU_SHOW."' WHERE admin_menu_link='option=com_easycomments&task=comments'");
$database->query();
$database->setQuery("UPDATE #__components SET name ='"._EASYCOMMENTS_INSTALL_MENU_SETTINGS."' WHERE admin_menu_link='option=com_easycomments&task=settings'");
$database->query();
$database->setQuery("UPDATE #__components SET name ='"._EASYCOMMENTS_INSTALL_MENU_ABOUT."' WHERE admin_menu_link='option=com_easycomments&task=about'");
$database->query();
$database->setQuery("UPDATE #__components SET name ='"._EASYCOMMENTS_INSTALL_MENU_MIGRATE."' WHERE admin_menu_link='option=com_easycomments&task=migrate'");
$database->query();

$seclistarray = explode (",", $ec_config['sectionlist']);
$database -> setQuery("SELECT id,title FROM #__sections ORDER BY title ASC");
$dbsectionlist = $database -> loadObjectList(); 

$grouplistarray = explode (",", $ec_config['fe_grouplist']);
$userslistarray = explode (",", $ec_config['fe_userslist']);
$database -> setQuery("SELECT `id`, `name`, `username`, `usertype` FROM `#__users` ORDER BY `usertype` DESC, `name` ASC");
$dbuserslist = $database -> loadObjectList(); 
	$query = "SELECT `name`"
	. "\n FROM #__core_acl_aro_groups"
	. "\n WHERE name != 'ROOT'"
	. "\n AND name != 'USERS'"
	. "\n AND name != 'Public Frontend'"
	. "\n AND name != 'Public Backend'"
	. "\n ORDER BY `lft` DESC";
	$database->setQuery( $query );
	$usertypes = $database->loadObjectList();

 HTML_comment::showConfig( $dbsectionlist, $seclistarray, $dbuserslist, $userslistarray, $usertypes, $grouplistarray, $ec_config, $option, $version);
}

############################################################################

function saveConfig ($option, $ec_config, $ec_mainmode, $ec_notify, $ec_emailcloak, $ec_frontendedit)
{
  global $mosConfig_absolute_path;
  $ec_config['mainmode'] = $ec_mainmode;
  $ec_config['notify'] = $ec_notify;
  $ec_config['emailcloak'] = $ec_emailcloak;
  $ec_config['frontendedit'] = $ec_frontendedit;
 
  $configfile = $mosConfig_absolute_path."/administrator/components/com_easycomments/config.easycomments.php";
  @chmod ($configfile, 0766);
  $permission = is_writable($configfile);
  if (!$permission) {
		mosRedirect("index2.php?option=$option&task=settings", _EASYCOMMENTS_ADMIN_NOTWRITABLE);
    break;
  }
  $ec_config['sectionlist']   = implode(',',mosGetParam( $_REQUEST, 'ec_selections', null ));
  $ec_config['fe_grouplist']   = implode(',',mosGetParam( $_REQUEST, 'ec_sel_groups', null ));
  $ec_config['fe_userslist']   = implode(',',mosGetParam( $_REQUEST, 'ec_sel_users', null ));
  $ec_config['\\\'show_readmore\\\''] = ( $ec_config['\\\'show_readmore\\\''] == 'on' ) ? 1 : 0;
	$config = "<?php\n";
	$config .= "\$ec_config" . "=" . "array(\n";
	foreach ($ec_config as $name=>$value)
	{
		$name = stripslashes($name);
		$name = str_replace("'","",$name);
		$config .= "\"$name\" => \"$value\",\n";
	}
	$config .= ");\n";
	$config .= "?>";
  if ($fp = fopen("$configfile", "w"))
  {
    fputs($fp, $config);
    fclose ($fp);
  }
//  print_r($ec_config);
//  die();
mosRedirect("index2.php?option=$option&task=settings", _EASYCOMMENTS_ADMIN_SAVED_SETTINGS);
}

############################################################################

function removeComments( $cid, $option ) {
  global $database;
  if (count( $cid )) {
    $cids = implode( ',', $cid );
    $database->setQuery( "DELETE FROM #__easycomments WHERE id IN ($cids)" );
    if (!$database->query()) {
		mosRedirect("index2.php?option=$option&task=config", $database->getErrorMsg());
    }
  }
  mosRedirect( "index2.php?option=$option" );
}

############################################################################

function showLanguage($option) {
  global $mosConfig_absolute_path, $mosConfig_lang;
  if (file_exists($mosConfig_absolute_path.'/components/com_easycomments/languages/'.$mosConfig_lang.'.php')) {
    $file = $mosConfig_absolute_path.'/components/com_easycomments/languages/'.$mosConfig_lang.'.php';
  } else {
    $file = $mosConfig_absolute_path.'/components/com_easycomments/languages/english.php';
  }
  @chmod ($file, 0766);
  $permission = is_writable($file);
  if (!$permission) {
    echo "<center><h1><font color=red>Warning...</FONT></h1><BR>";
    echo "<B>You need to chmod the file to 766 in order to save your updates.</B></center><BR />";
  }
  HTML_comment::showFile($file,$option);
}
function saveLanguage($file, $filecontent, $option) {
  @chmod ($file, 0766);
  $permission = is_writable($file);
  if (!$permission) {
    mosRedirect("index2.php?option=$option&task=language", "File not writeable!");
    break;
  }
  if ($fp = fopen( $file, "w")) {
    fputs($fp,stripslashes($filecontent));
    fclose($fp);
    mosRedirect( "index2.php?option=$option&task=language", "Language file saved" );
  }
}